package cn.sylinx.horm.example.section7;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;
import java.util.Map;

import cn.sylinx.horm.core.SqlClient;
import cn.sylinx.horm.core.interceptor.SqlClientInterceptor;
import cn.sylinx.horm.interceptor.Invocation;
import cn.sylinx.horm.resource.ClasspathSqlResource;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestSqlClientInterceptor implements SqlClientInterceptor {

    @SuppressWarnings({ "unchecked" })
    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        Method method = invocation.getMethod();
        Parameter[] parameters = method.getParameters();

        if ("queryList".equals(method.getName()) //
                && parameters != null //
                && parameters.length == 3 //
                && (parameters[0].getType() == ClasspathSqlResource.class) //
                && (parameters[1].getType() == Map.class)) {

            /**
             * 拦截方法
             * 
             * <pre>
             * public <T> List<T> queryList(ClasspathSqlResource sqlResource, Map<String, Object> params,
             *         Class<T> modelClass);
             * </pre>
             */
            SqlClient sqlClient = (SqlClient) invocation.getTarget();
            String dbtype = sqlClient.getDialect().getDbType().getValue();
            log.info("拦截到方法，将当前数据库类型[{}]放入参数中", dbtype);

            Object[] args = invocation.getArgs();
            if (args[1] == null) {
                args[1] = new HashMap<String, Object>();
            }
            // 将当前数据库类型放入参数中
            ((Map<String, Object>) args[1]).put("dbtype", dbtype);
        }

        return invocation.proceed();
    }

}
